package handlers

import (
	"context"
	"ourplansystem/server/ent"
	"ourplansystem/server/models"
	"strconv"
	"time"

	"github.com/gofiber/fiber/v2"
)

// GoalHandler 共同目标处理器
type GoalHandler struct {
	client *ent.Client
}

// NewGoalHandler 创建共同目标处理器
func NewGoalHandler(client *ent.Client) *GoalHandler {
	return &GoalHandler{client: client}
}

// CreateGoalRequest 创建目标请求
type CreateGoalRequest struct {
	Title        string  `json:"title"`
	Type         string  `json:"type"`
	TargetValue  float64 `json:"target_value"`
	CurrentValue float64 `json:"current_value"`
	Unit         string  `json:"unit"`
	Deadline     string  `json:"deadline"` // 格式: 2006-01-02
}

// UpdateGoalRequest 更新目标请求
type UpdateGoalRequest struct {
	Title        string  `json:"title"`
	Type         string  `json:"type"`
	TargetValue  float64 `json:"target_value"`
	CurrentValue float64 `json:"current_value"`
	Unit         string  `json:"unit"`
	Deadline     string  `json:"deadline"`
	Status       string  `json:"status"`
}

// GetGoals 获取所有目标
func (h *GoalHandler) GetGoals(c *fiber.Ctx) error {
	ctx := context.Background()
	goals, err := h.client.Goal.Query().All(ctx)
	if err != nil {
		return models.InternalServerError(c, "获取目标列表失败")
	}

	return models.Success(c, goals)
}

// GetGoal 获取单个目标
func (h *GoalHandler) GetGoal(c *fiber.Ctx) error {
	ctx := context.Background()
	id, err := strconv.ParseInt(c.Params("id"), 10, 64)
	if err != nil {
		return models.BadRequest(c, "无效的目标ID")
	}

	goal, err := h.client.Goal.Get(ctx, id)
	if err != nil {
		if ent.IsNotFound(err) {
			return models.NotFound(c, "目标不存在")
		}
		return models.InternalServerError(c, "获取目标失败")
	}

	return models.Success(c, goal)
}

// CreateGoal 创建目标
func (h *GoalHandler) CreateGoal(c *fiber.Ctx) error {
	ctx := context.Background()
	var req CreateGoalRequest
	if err := c.BodyParser(&req); err != nil {
		return models.BadRequest(c, "请求参数错误")
	}

	if req.Title == "" {
		return models.BadRequest(c, "标题不能为空")
	}

	builder := h.client.Goal.
		Create().
		SetTitle(req.Title).
		SetTargetValue(req.TargetValue).
		SetCurrentValue(req.CurrentValue)

	if req.Type != "" {
		builder.SetType(req.Type)
	}

	if req.Unit != "" {
		builder.SetUnit(req.Unit)
	}

	if req.Deadline != "" {
		deadline, err := time.Parse("2006-01-02", req.Deadline)
		if err != nil {
			return models.BadRequest(c, "截止日期格式错误，应为: 2006-01-02")
		}
		builder.SetDeadline(deadline)
	}

	goal, err := builder.Save(ctx)
	if err != nil {
		return models.InternalServerError(c, "创建目标失败")
	}

	return models.SuccessWithMessage(c, "创建成功", goal)
}

// UpdateGoal 更新目标
func (h *GoalHandler) UpdateGoal(c *fiber.Ctx) error {
	ctx := context.Background()
	id, err := strconv.ParseInt(c.Params("id"), 10, 64)
	if err != nil {
		return models.BadRequest(c, "无效的目标ID")
	}

	var req UpdateGoalRequest
	if err := c.BodyParser(&req); err != nil {
		return models.BadRequest(c, "请求参数错误")
	}

	builder := h.client.Goal.UpdateOneID(id)

	if req.Title != "" {
		builder.SetTitle(req.Title)
	}

	if req.Type != "" {
		builder.SetType(req.Type)
	}

	if req.TargetValue > 0 {
		builder.SetTargetValue(req.TargetValue)
	}

	if req.CurrentValue >= 0 {
		builder.SetCurrentValue(req.CurrentValue)
	}

	if req.Unit != "" {
		builder.SetUnit(req.Unit)
	}

	if req.Deadline != "" {
		deadline, err := time.Parse("2006-01-02", req.Deadline)
		if err != nil {
			return models.BadRequest(c, "截止日期格式错误")
		}
		builder.SetDeadline(deadline)
	}

	if req.Status != "" {
		builder.SetStatus(req.Status)
	}

	goal, err := builder.Save(ctx)
	if err != nil {
		if ent.IsNotFound(err) {
			return models.NotFound(c, "目标不存在")
		}
		return models.InternalServerError(c, "更新目标失败")
	}

	return models.SuccessWithMessage(c, "更新成功", goal)
}

// DeleteGoal 删除目标
func (h *GoalHandler) DeleteGoal(c *fiber.Ctx) error {
	ctx := context.Background()
	id, err := strconv.ParseInt(c.Params("id"), 10, 64)
	if err != nil {
		return models.BadRequest(c, "无效的目标ID")
	}

	err = h.client.Goal.DeleteOneID(id).Exec(ctx)
	if err != nil {
		if ent.IsNotFound(err) {
			return models.NotFound(c, "目标不存在")
		}
		return models.InternalServerError(c, "删除目标失败")
	}

	return models.SuccessWithMessage(c, "删除成功", nil)
}
